const {
  scanQrCode,
  getWorkOrderIdByQrCodeId
} = require('../api/qrcode')
const {
  getUserKind
} = require('../utils/strorage')
const {
  getAssetsByScanQrCodeId
} = require('../api/assets')
const {
  to,
  openLoading,
  closeLoading,
  routeWithToken,
  showToast
} = getApp()
const {
  TARGET_PAGE_TYPE
} = require('../constant/index')
Page({
  data: {

  },
  onLoad() {
    const type = this.options.type;
    const userType = getUserKind();

    if (type === 'orderRecord') {
      let url = '/page-client/order-history/index'
      if (userType === 'repair') {
        url = '/page-repair/my-order/index'
      }

      routeWithToken(url, true)

      return;
    }

    this.getScanQrCode()
  },
  getQrCode() {
    let code = '';
    try {
      const query = decodeURIComponent(this.options.q);
      const param = query.split('?')[0];
      const list = param.split('/')
      code = list[list.length - 1];
    } catch(e) {}

    return code
  },
  async getScanQrCode() {
    const code = this.getQrCode()
    if (!code && code !== 0 || code === 'undefined') {
      showToast('二维码无效');
      return
    }
    openLoading()
    const [err, data] = await to(scanQrCode(code))
    if (!err) {
      this.getWorkOrderId(data)
    } else {
      closeLoading()
    }
  },

  async getWorkOrderId(item) {
    const route = this.getRouteUrl(item)
    closeLoading()
    if (!route) return
    if (item.targetPageType === TARGET_PAGE_TYPE.createOrder) {
      this.getDeviceInfo()
    } else {
      routeWithToken(route, true)
    }
  },

  async getDeviceInfo() {
    const params = {
      qrCodeId: this.getQrCode()
    }
    openLoading()
    const [err, data] = await to(getAssetsByScanQrCodeId(params))
    closeLoading()
    if (!err) {

      wx.setStorageSync('device-manager', JSON.stringify(data))
      routeWithToken('/page-repair/device-manager/device-form/index?type=review&isscan=true&code=' + params.qrCodeId)
    }
  },

  getRouteUrl(item) {
    let route = ''
    const targetPageType = item.targetPageType
    switch (targetPageType) {
      case TARGET_PAGE_TYPE.index:
        route = '/tabbar/index/index'
        break;
      case TARGET_PAGE_TYPE.createOrder:
        route = '/page-common/repair-page/index?qrCode=' + item.qrCodeId
        break;
      case TARGET_PAGE_TYPE.orderDetail:
      case TARGET_PAGE_TYPE.scanCode:
        this.getOrderIdByQrCode(item)
    }

    return route
  },

  async getOrderIdByQrCode(item) {
    const [err, data] = await to(getWorkOrderIdByQrCodeId({ qrCodeId: item.qrCodeId }));
    closeLoading()

    if (!err) {
      routeWithToken('/page-common/order-page/index?workOrderId=' + data, true)
    }
  }
})